package com.pr.makfilm.dao.impl;

import com.pr.makfilm.dao.IRoomDao;
import com.pr.makfilm.domain.ObjectStateEnum;
import com.pr.makfilm.domain.Room;
import com.pr.makfilm.domain.User;
import com.pr.makfilm.domain.filter.AbstractFilter;
import com.pr.makfilm.domain.filter.RoomFilter;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Pawel
 * Date: 17.09.13
 * Time: 23:00
 * To change this template use File | Settings | File Templates.
 */
@Repository(RoomDaoImpl.BEAN_NAME)
public class RoomDaoImpl extends AbstractDaoImpl<Room> implements IRoomDao
{
   public static final String BEAN_NAME = "roomDao";

   @Override
   public Criteria createCriteriaFromSearchParams(AbstractFilter abstractFilter)
   {
      Criteria criteria = createCriteria();
      RoomFilter filter = (RoomFilter) abstractFilter;
      String name = filter.getName();
      if (name != null)
      {
         criteria.add(Restrictions.ilike(Room.FIELD_NAME, name, MatchMode.ANYWHERE));
      }
      String city = filter.getCity();
      if (city != null)
      {
         criteria.add(Restrictions.eq(Room.FIELD_CITY, city));
      }
      User user = filter.getUser();
      if (user != null)
      {
         criteria.add(Restrictions.eq(Room.FIELD_USER, user));
      }
      ObjectStateEnum objectState = filter.getObjectState();
      if (objectState != null)
      {
         criteria.add(Restrictions.eq(Room.FIELD_OBJECT_STATE, objectState));
      }
      return criteria;
   }

   @Override
   public List<String> findRoomCities(User user)
   {
      Criteria criteria = createCriteria();
      criteria.add(Restrictions.eq(Room.FIELD_USER, user));
      criteria.add(Restrictions.eq(Room.FIELD_OBJECT_STATE, ObjectStateEnum.ACTIVE));
      criteria.setProjection(Projections.distinct(Projections.property(Room.FIELD_CITY)));
      return criteria.list();
   }
}
